package com.juneng.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * HttpClient工具类
 *
 * @author zsl
 *
 */
@SuppressWarnings("deprecation")
public abstract class HttpClientUtil {

    /**
     * HTTP GET请求
     *
     * @param url
     *            地址
     * @param params
     *            参数
     * @param encoding
     *            编码
     * @return response
     */
    public static String doGet(String url, Map<String, String> params, String encoding) {
        /* 断言编码是否为空 */
        if (encoding == null) {
            // 默认编码ISO-8859-1
            encoding = HTTP.DEFAULT_CONTENT_CHARSET;
        }
        // 构造HttpClient实例
        HttpClient httpClient = null;
        // 创建GET方法实例
        HttpGet httpGet = new HttpGet(url);
        // 响应信息
        String responseBody = null;
        // 参数实体类
        HttpEntity entity = null;
        try {
            httpClient = new DefaultHttpClient();
            /* 设置参数 */
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Entry<String, String> elem : params.entrySet()) {
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                String str = EntityUtils.toString(new UrlEncodedFormEntity(list, encoding));
                httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
            }

            // 执行GET请求
            HttpResponse httpResponse = httpClient.execute(httpGet);
            /* 获取返回数据 */
            if (httpResponse != null) {
                entity = httpResponse.getEntity();
                responseBody = EntityUtils.toString(entity, encoding);
            }

        } catch (Exception e) {
            System.err.println("执行GET请求:" + e);
        } finally {
            // 关闭InputStream流
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                System.err.println("关闭InputStream流异常:" + e);
            }
            // 关闭HttpClient连接
            if(httpClient != null) httpClient.getConnectionManager().shutdown();
        }
        return responseBody;
    }

    /**
     * HTTP POST请求
     *
     * @param url url
     * @param params params map
     * @param encoding encode
     * @return response
     */
    public static String doPost(String url, Map<String, String> params, String encoding) throws IOException {
        /* 断言编码是否为空 */
        if (encoding == null) {
            // 默认编码ISO-8859-1
            encoding = HTTP.DEFAULT_CONTENT_CHARSET;
        }
        // 构造HttpClient实例
        HttpClient httpClient = null;
        // 响应信息
        String responseBody = null;
        // 参数实体类
        HttpEntity httpEntity = null;
        try {
            httpClient = new DefaultHttpClient();
            // 创建POST方法实例
            HttpPost httpPost = new HttpPost(url);
            /* 设置参数 */
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, encoding);
                httpPost.setEntity(formEntity);
            }
            // 执行POST请求
            HttpResponse httpResponse = httpClient.execute(httpPost);
            /* 获取返回数据 */
            if (httpResponse != null) {
                httpEntity = httpResponse.getEntity();
                responseBody = EntityUtils.toString(httpEntity, encoding);
            }
        } catch (Exception e) {
            System.err.println("执行POST请求异常:" + e);
        } finally {
            try {
                // 关闭InputStream流
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                System.err.println("关闭InputStream流异常:" + e);
            }
            // 关闭HttpClient连接
            if(httpClient != null) httpClient.getConnectionManager().shutdown();
        }
        return responseBody;
    }
}
